<template>
  <el-row align="middle" :gutter="10">
    <el-col :span="4">背景</el-col>
    <el-col :span="14">
      <el-select v-model="background" @change="handleChangeBackGround">
        <el-option label=" " value="null" />
        <el-option label="COLOR" value="COLOR" />
        <el-option label="TEXTURE" value="TEXTURE" />
        <el-option label="EQUIRECT" value="EQUIRECT" />
      </el-select>
    </el-col>
    <el-col :span="6">
      <el-color-picker
        v-if="background === 'COLOR'"
        v-model="color"
        @active-change="handleChangeColor"
      />
      <BUpload
        v-else-if="background === 'TEXTURE'"
        v-model="texturePath"
        @change="handleChangeTexture"
      ></BUpload>
      <BUpload
        v-else-if="background === 'EQUIRECT'"
        v-model="equirectPath"
        @change="handleChangeEquirect"
      ></BUpload>
    </el-col>
  </el-row>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { useViewportStore } from '@renderer/stores/viewport'
import { storeToRefs } from 'pinia'
import { Color, EquirectangularReflectionMapping } from 'three'
import BUpload from '@renderer/components/b-upload.vue'
import useTexture from '@renderer/utils/useTexture'

const background = ref(' ')
const color = ref('')
const texturePath = ref('')
const equirectPath = ref('')
const viewportStore = useViewportStore()
const { scene } = storeToRefs(viewportStore)

async function handleChangeBackGround(option: string) {
  if (scene.value) {
    scene.value.background = null
    switch (option) {
      case 'COLOR':
        if (color.value) {
          scene.value.background = new Color(color.value)
        }
        break
      case 'TEXTURE':
        if (texturePath.value) {
          const texture = await useTexture(texturePath.value)
          scene.value.background = texture
        }
        break
      case 'EQUIRECT':
        if (equirectPath.value) {
          const texture = await useTexture(equirectPath.value)
          texture.mapping = EquirectangularReflectionMapping
          scene.value.background = texture
        }
        break
    }
  }
}

function handleChangeColor(color: string) {
  if (scene.value) {
    scene.value.background = new Color(color)
  }
}

async function handleChangeTexture(url: string) {
  texturePath.value = url
  if (scene.value) {
    const texture = await useTexture(url)
    scene.value.background = texture
  }
}

async function handleChangeEquirect(url: string) {
  equirectPath.value = url
  if (scene.value) {
    const texture = await useTexture(url)
    texture.mapping = EquirectangularReflectionMapping
    scene.value.background = texture
  }
}
</script>
<style lang="scss" scoped></style>
